# -*- coding=utf-8 -*-

import time


# 获取日期字符串
def get_date_str(num=0, date_format='%d.%m.%y'):
    now_timestamp = time.time() + (num * 24 * 3600)
    now_time_tuple = time.localtime(now_timestamp)
    now_date_str = time.strftime(date_format, now_time_tuple)
    return now_date_str


# 默认当前时间
def time_2_second(time_str=None):
    if time_str is None:
        h = int(time.strftime('%H'))
        m = int(time.strftime('%M'))
        s = int(time.strftime('%S'))
    else:
        time.strftime('%F') + ' ' + time_str
        time_struct = time.strptime(time.strftime('%F') + ' ' + time_str, '%Y-%m-%d %H:%M:%S')
        h = int(time.strftime('%H', time_struct))
        m = int(time.strftime('%M', time_struct))
        s = int(time.strftime('%S', time_struct))
    hs = h * 3600
    ms = m * 60
    second = hs + ms + s
    return second


def second_2_time(sec):
    h = int(sec / 3600)
    hs = h * 3600
    m = int((sec - hs) / 60)
    ms = m * 60
    s = int(sec - hs - ms)
    time_string = zero_fix(h) + ':' + zero_fix(m) + ':' + zero_fix(s)
    return time_string


# 被0，默认前补0
def zero_fix(int_val):
    val = str(int_val)
    if int_val < 10:
        val = '0' + val
    return val


def string_to_timestamp(time_string, time_format='%Y-%m-%d %H:%M:%S'):
    return time.mktime(time.strptime(time_string, time_format))


def get_timestamp_from_string(time_str, time_format='%Y-%m-%d %H:%M:%S'):
    return time.mktime(time.strptime(time_str, time_format))


def calc_time_lag(start_time_str, end_time_str, time_format='%Y-%m-%d %H:%M:%S'):
    return int(
        round(
            get_timestamp_from_string(end_time_str, time_format) -
            get_timestamp_from_string(start_time_str, time_format)
        )
    )


def calc_planned_num(target_num, passed_second, total_second):
    return int(target_num / total_second * passed_second) if passed_second > 0 else '-'


def calc_forecast_num(current_num, passed_second, total_second):
    return int(current_num / passed_second * total_second) if passed_second > 0 else '-'


def to_int(val):
    n = 0
    if type(val) is int:
        n = val
    return n


def get_tomorrow_time_str():
    import datetime
    now_time = datetime.datetime.now()
    tomorrow_time = now_time + datetime.timedelta(days=1)
    return tomorrow_time.strftime('%Y%m%d000000')


def get_week_first_date_str(date_str, num=1):
    date_tuple = time.strptime(date_str, '%Y-%m-%d')
    week_day_number = int(time.strftime('%w', date_tuple))
    date_timestamp = int(time.mktime(date_tuple))
    week_first_day_timestamp = date_timestamp - (week_day_number - num) * 3600 * 24
    week_first_day_time_tuple = time.localtime(week_first_day_timestamp)
    return time.strftime('%Y-%m-%d', week_first_day_time_tuple)


# 获取以小时为单位的时间范围。
# 比如获取上一小时的时间范围，当前时间为10:30，返回9-10点的时间范围
def get_hour_range(date_str, hour=0):
    hour_str = time.strftime('%H')
    date_tuple = time.strptime(date_str + ' ' + hour_str, '%Y-%m-%d %H')
    date_timestamp = int(time.mktime(date_tuple))
    from_timestamp = date_timestamp + hour * 3600
    from_time_tuple = time.localtime(from_timestamp)
    from_time = time.strftime('%Y-%m-%d %H', from_time_tuple) + ':00:00'
    time_range = {'from_time': from_time}
    if hour == 0:
        time_range['to_time'] = time.strftime('%Y-%m-%d %H:%M:%S')
    else:
        to_timestamp = date_timestamp + (hour + 1) * 3600
        to_time_tuple = time.localtime(to_timestamp)
        time_range['to_time'] = time.strftime('%Y-%m-%d %H', to_time_tuple) + ':00:00'
    return time_range


def timestamp_2_str(timestamp, time_format='%Y%m%d'):
    time_tuple = time.localtime(timestamp)
    return time.strftime(time_format, time_tuple)


def is_date(text, pattern=r'\d{4}\-\d{2}-\d{2}'):
    bl = False
    if isinstance(text, str):
        import re
        bl = re.match(pattern, text) is not None
    return bl


def compute_the_time_difference(time1, time2, fmt='%Y-%m-%d %H:%M:%S'):
    tt1 = time.strptime(time1, fmt)
    tt2 = time.strptime(time2, fmt)
    ts1 = int(time.mktime(tt1))
    ts2 = int(time.mktime(tt2))
    return ts2 - ts1


# 获取一周的起始及结束日期，默认从周一取到周六
def get_week_range(date_str, fmt='%Y-%m-%d %H:%M:%S', num=7):
    time_tuple = time.strptime(date_str, fmt)
    timestamp = int(time.mktime(time_tuple))
    week_num = int(time.strftime('%w', time_tuple))
    if week_num == 0:
        week_num = 7
    day_second = 86400
    the_week_start_timestamp = timestamp - (week_num - 1) * day_second
    the_week_end_timestamp = the_week_start_timestamp + 86400 * num
    the_week_start_tuple = time.localtime(the_week_start_timestamp)
    the_week_end_tuple = time.localtime(the_week_end_timestamp)
    the_week_start_time_str = time.strftime(fmt, the_week_start_tuple)
    the_week_end_time_str = time.strftime(fmt, the_week_end_tuple)
    return {
        'start': the_week_start_time_str,
        'end': the_week_end_time_str
    }


def reformat_date_str(time_string, time_format='%Y-%m-%d %H:%M:%S', new_time_format='%Y-%m-%d'):
    tt = time.strptime(time_string, time_format)
    return time.strftime(new_time_format, tt)


def is_date_in_range(date_str, range_start, range_end, fmt='%Y-%m-%d %H:%M:%S'):
    date_timestamp = string_to_timestamp(date_str, fmt)
    start_timestamp = string_to_timestamp(range_start, fmt)
    end_timestamp = string_to_timestamp(range_end, fmt)
    result = False
    if start_timestamp <= date_timestamp < end_timestamp:
        result = True
    return result


def str2numeric(str):
    import re
    pattern = r'[^\d]'
    return re.sub(pattern, '', str)


def reformat_date_str(time_string, time_format='%Y-%m-%d %H:%M:%S', new_time_format='%Y-%m-%d'):
    tt = time.strptime(time_string, time_format)
    return time.strftime(new_time_format, tt)


def get_the_shift_range(shift_range_list):
    today_date_str = time.strftime('%Y%m%d', time.localtime())
    today_time_str = time.strftime('%H%M', time.localtime())
    yesterday_date_str = time.strftime('%Y%m%d',
                                       time.localtime(time.mktime(time.strptime(today_date_str, '%Y%m%d')) - 3600 * 24))
    tomorrow_date_str = time.strftime('%Y%m%d',
                                      time.localtime(time.mktime(time.strptime(today_date_str, '%Y%m%d')) + 3600 * 24))
    shift_range_dict = None
    for time_dict in shift_range_list:
        time_from = time_dict.get('from')
        time_to = time_dict.get('to')
        numeric_time_from = str2numeric(time_from)
        numeric_time_to = str2numeric(time_to)
        int_time_from = int(numeric_time_from)
        int_time_to = int(numeric_time_to)
        int_current_time = int(today_time_str)
        if int_time_from > int_time_to:
            if int_current_time > int_time_to:
                int_datetime_from = int(today_date_str + numeric_time_from)
                int_datetime_to = int(tomorrow_date_str + numeric_time_to)
            else:
                int_datetime_from = int(yesterday_date_str + numeric_time_from)
                int_datetime_to = int(today_date_str + numeric_time_to)
        else:
            int_datetime_from = int(today_date_str + numeric_time_from)
            int_datetime_to = int(today_date_str + numeric_time_to)
        int_datetime_current = int(today_date_str + today_time_str)
        if int_datetime_from <= int_datetime_current < int_datetime_to:
            str_datetime_from = reformat_date_str(str(int_datetime_from), '%Y%m%d%H%M', '%Y-%m-%d %H:%M:%S')
            str_datetime_to = reformat_date_str(str(int_datetime_to), '%Y%m%d%H%M', '%Y-%m-%d %H:%M:%S')
            shift_range_dict = {'from': str_datetime_from, 'to': str_datetime_to}
    return shift_range_dict
